package com.woniu.order.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.bean.R;
import com.woniu.order.bean.*;
import com.woniu.order.service.ITCostService;
import com.woniu.order.service.ITOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellowDocter
 * @since 2022-08-09
 */
@CrossOrigin
@RestController
@RequestMapping("/tCost")
public class TCostController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ITCostService itCostService;
    @Autowired
    private ITOrderService itOrderService;
    @PostMapping
    public R add(@RequestBody TCost tCost) {
        System.out.println("TCostController.add");
        System.out.println("tCost = " + tCost);
        String costKey = "cost:"+ tCost.getOrderId() + ":save";
        String s = stringRedisTemplate.opsForValue().get(costKey);
            String s1 = null;
            try {
                s1 = objectMapper.writeValueAsString(tCost);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            stringRedisTemplate.opsForValue().set(costKey,s1);
            R r=null;
            if(StringUtils.hasText(stringRedisTemplate.opsForValue().get(costKey))){
                r=R.OK();
            } else {
                r=R.ERROR();
            }
            return r;
       
    }
    
    @GetMapping
    public R load() throws JsonProcessingException {

        R r= null;
        List<TOrder> list = itOrderService.list();
        Integer orderId = list.get(list.size() - 1).getOrderId();
        orderId+=1;
        String costKey = "cost:"+ orderId + ":save";
        String s = stringRedisTemplate.opsForValue().get(costKey);
        if(StringUtils.hasText(s)){
            TCost tCost = objectMapper.readValue(s, TCost.class);
            r=R.OK();
            Map map=new HashMap<>();
            map.put("tCost", tCost);
            r.setData(map);
        }

        return r;
    }

}
